package com.oyjd.ybx.front.action;

import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.ServletRequestUtils;

import com.oyjd.ybx.bean.vo.UserVO;
import com.oyjd.ybx.business.classify.service.ClassifyService;
import com.oyjd.ybx.business.suggest.service.SuggestService;
import com.oyjd.ybx.business.user.service.UserService;
import com.oyjd.ybx.front.service.FrontSysService;
import com.oyjd.ybx.fw.action.BaseAction;
import com.oyjd.ybx.fw.util.CheckPic;
import com.oyjd.ybx.fw.util.CodeUtil;
import com.oyjd.ybx.fw.util.FileOP;
import com.oyjd.ybx.fw.util.OutUtil;
import com.oyjd.ybx.fw.util.SecretUtil;
import com.oyjd.ybx.fw.util.SecurityUtil;
import com.oyjd.ybx.pub.Const;

/**
 * 
 * 前端Action控制层
 * 
 * @author <b>欧建东<br/>
 *         Email:oyjd@163.com</b>
 * @version 1.0
 */
@Action(value = "/frontSys")
@Results({ @Result(name = "viewLogin", location = Const.JSP_front_login), @Result(name = "viewRegist", location = Const.JSP_front_regist), @Result(name = "goFindPwd", location = Const.JSP_front_goFindPwd), @Result(name = "showInfo", location = Const.JSP_front_showInfo), @Result(name = "goResetPwd", location = Const.JSP_front_goResetPwd), @Result(name = "viewBabyInfo", location = Const.JSP_front_goBabyInfo), @Result(name = "viewSuggest", location = Const.JSP_front_suggest) })
public class FrontSysAction extends BaseAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = 654347027015039L;

	private static final String secretPwd = "oyjd@163.com";

	private static final String SPLIT = "--!--";

	private static final Log log = LogFactory.getLog(FrontSysAction.class);

	private ClassifyService classifyService;

	private UserService userService;

	private FrontSysService frontSysService;

	private SuggestService suggestService;

	@Autowired
	public void setSuggestService(SuggestService suggestService) {
		this.suggestService = suggestService;
	}

	@Autowired
	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	@Autowired
	public void setClassifyService(ClassifyService classifyService) {
		this.classifyService = classifyService;
	}

	@Autowired
	public void setFrontSysService(FrontSysService frontSysService) {
		this.frontSysService = frontSysService;
	}

	/**
	 * 进入登陆页面
	 * 
	 * @return
	 */
	public String viewLogin() {
		// 分类树
		getRequest().setAttribute("treeMap", classifyService.getFrontClass());
		return "viewLogin";
	}

	/**
	 * 进入注册页面
	 * 
	 * @return
	 */
	public String viewRegist() {
		// 分类树
		getRequest().setAttribute("treeMap", classifyService.getFrontClass());
		return "viewRegist";
	}

	/**
	 * 用户登入
	 * 
	 * @return
	 */
	public String login() {
		Map<String, Object> map = CodeUtil.getJsonMap();
		try {
			HttpServletRequest req = getRequest();
			HttpServletResponse res = getResponse();
			String uid = ServletRequestUtils.getStringParameter(req, "uid");
			String pwd = ServletRequestUtils.getStringParameter(req, "pwd");
			String checkCode = ServletRequestUtils.getStringParameter(req, "checkCode");
			String remember = ServletRequestUtils.getStringParameter(req, "remember", "0");

			pwd = SecurityUtil.encoderByMd5(pwd);
			UserVO vo = userService.getUserByAccount(uid);
			if (null != vo && uid.equals(vo.getAccount()) && pwd.equals(vo.getPwd())) {
				String code = (String) session.get(CodeUtil.CheckCode);
				if (code.equalsIgnoreCase(checkCode)) {
					if ("1".equals(remember)) {
						res.addCookie(toCookie(vo.getAccount(), vo.getPwd()));
					}
					session.put(CodeUtil.SessionKey, vo);
					map.put("code", CodeUtil.SUCCESS);
				}
			}

		} catch (Exception err) {
			log.error(err.getMessage(), err);
			map.put("code", CodeUtil.UNKOWN_ERR);
		}
		OutUtil.outJson(map, getResponse());
		return null;
	}

	/**
	 * 验证登入
	 * 
	 * @return
	 */
	public String checkToken() {
		Map<String, Object> map = CodeUtil.getJsonMap();
		try {
			HttpServletRequest req = getRequest();
			Cookie[] cookies = req.getCookies();
			if (null != cookies) {
				for (Cookie cookie : cookies) {
					if (CodeUtil.CookieKey.equals(cookie.getName())) {
						String v = cookie.getValue();
						String vv = URLDecoder.decode(v, "UTF-8");
						String s = SecretUtil.decrypt(vv, secretPwd);
						String[] a = s.split(SPLIT);
						String uid = a[0];
						String pwd = a[1];
						UserVO vo = userService.getUserByAccount(uid);
						if (null != vo && pwd.equals(vo.getPwd())) {
							session.put(CodeUtil.SessionKey, vo);
							map.put("info", vo);
							map.put("code", CodeUtil.SUCCESS);
						}
						break;
					}
				}
			}
		} catch (Exception err) {
			log.error(err.getMessage(), err);
			map.put("code", CodeUtil.UNKOWN_ERR);
		}
		OutUtil.outJson(map, getResponse());
		return null;
	}

	/**
	 * 登出
	 * 
	 * @return
	 * @throws IOException
	 */
	public String loginOut() throws IOException {
		Map<String, Object> map = CodeUtil.getJsonMap();
		try {
			HttpServletRequest req = getRequest();
			HttpServletResponse res = getResponse();
			session.clear();
			req.getSession().invalidate();
			//
			Cookie cookie = new Cookie(CodeUtil.CookieKey, null);
			cookie.setMaxAge(0);
			res.addCookie(cookie);
			map.put("code", CodeUtil.SUCCESS);
		} catch (Exception err) {
			log.error(err.getMessage(), err);
			map.put("code", CodeUtil.UNKOWN_ERR);
		}
		OutUtil.outJson(map, getResponse());
		return null;
	}

	/**
	 * 获取图形验证码
	 * 
	 * @return
	 */
	public String getCheckPic() {
		try {
			CheckPic.ImgVO vo = CheckPic.getImage();
			HttpServletResponse res = getResponse();
			res.setHeader("Pragma", "No-cache");
			res.setHeader("Cache-Control", "no-cache");
			res.setDateHeader("Expires", 0);
			session.put(CodeUtil.CheckCode, vo.getCode());
			ImageIO.write(vo.getImg(), "JPEG", res.getOutputStream());
		} catch (Exception err) {
			log.error(err.getMessage(), err);
		}
		return null;
	}

	/**
	 * 检测帐号是否存在
	 * 
	 * @return
	 */
	public String checkAccount() {
		Map<String, Object> map = CodeUtil.getJsonMap();
		try {
			HttpServletRequest req = getRequest();
			String uid = ServletRequestUtils.getStringParameter(req, "uid");
			UserVO vo = userService.getUserByAccount(uid);
			if (null != vo) {
				map.put("code", CodeUtil.SUCCESS);
			}
		} catch (Exception err) {
			log.error(err.getMessage(), err);
			map.put("code", CodeUtil.UNKOWN_ERR);
		}
		OutUtil.outJson(map, getResponse());
		return null;
	}

	/**
	 * 注册
	 * 
	 * @return
	 */
	public String regist() {
		Map<String, Object> map = CodeUtil.getJsonMap();
		try {
			HttpServletRequest req = getRequest();
			HttpServletResponse res = getResponse();
			String uid = ServletRequestUtils.getStringParameter(req, "uid");
			String pwd = ServletRequestUtils.getStringParameter(req, "pwd");
			String sex = ServletRequestUtils.getStringParameter(req, "sex");
			String name = ServletRequestUtils.getStringParameter(req, "name");
			//
			pwd = SecurityUtil.encoderByMd5(pwd);
			userService.addFront("customer", uid, pwd, name, sex, uid);
			UserVO vo = userService.getUserByAccount(uid);
			res.addCookie(toCookie(vo.getAccount(), vo.getPwd()));
			session.put(CodeUtil.SessionKey, vo);
			map.put("code", CodeUtil.SUCCESS);
		} catch (Exception err) {
			log.error(err.getMessage(), err);
			map.put("code", CodeUtil.UNKOWN_ERR);
		}
		OutUtil.outJson(map, getResponse());
		return null;
	}

	/**
	 * 进入密码找回页面
	 * 
	 * @return
	 */
	public String goFindPwd() {
		// 分类树
		getRequest().setAttribute("treeMap", classifyService.getFrontClass());
		return "goFindPwd";
	}

	/**
	 * 发送密码找回页面的邮件
	 * 
	 * @return
	 */
	public String sentFindPwdMail() {
		Map<String, Object> map = CodeUtil.getJsonMap();
		try {
			HttpServletRequest req = getRequest();
			String uid = ServletRequestUtils.getStringParameter(req, "uid");
			UserVO vo = userService.getUserByAccount(uid);
			if (null != vo) {
				String key = SecretUtil.encrypt(uid + SPLIT + System.currentTimeMillis(), secretPwd);
				frontSysService.sentMail(vo, key);
				map.put("code", CodeUtil.SUCCESS);
			}
		} catch (Exception err) {
			log.error(err.getMessage(), err);
			map.put("code", CodeUtil.UNKOWN_ERR);
		}
		OutUtil.outJson(map, getResponse());
		return null;
	}

	/**
	 * 进入密码找回发送邮件成功页面
	 * 
	 * @return
	 */
	public String goSendOk() {
		// 分类树
		getRequest().setAttribute("treeMap", classifyService.getFrontClass());
		getRequest().setAttribute("info", "密码找回的信息已发送至您的邮箱（1小时内有效）！");
		return "showInfo";
	}

	/**
	 * 进入密码重置页面
	 * 
	 * @return
	 */
	public String goResetPwd() {
		// 分类树
		getRequest().setAttribute("treeMap", classifyService.getFrontClass());

		try {
			HttpServletRequest req = getRequest();
			String key = ServletRequestUtils.getStringParameter(req, "key", "");
			if (null != key && !"".equals(key)) {
				key = key.replaceAll(" ", "+");
				String temp = SecretUtil.decrypt(key, secretPwd);
				String[] keys = temp.split(SPLIT);
				long time = Long.parseLong(keys[1]);
				if (System.currentTimeMillis() - time <= 3600000) {// 1小时以内
					req.setAttribute("key", key);
					return "goResetPwd";
				}
			}
		} catch (Exception err) {
			log.error(err.getMessage(), err);
		}
		getRequest().setAttribute("info", "密码重置页面已经失效！");
		return "showInfo";
	}

	/**
	 * 重置密码
	 * 
	 * @return
	 */
	public String resetPwd() {
		// 分类树
		getRequest().setAttribute("treeMap", classifyService.getFrontClass());

		String info = "";
		try {
			HttpServletRequest req = getRequest();
			String pwd = ServletRequestUtils.getStringParameter(req, "pwd");
			String key = ServletRequestUtils.getStringParameter(req, "key", "");
			if (null != key && !"".equals(key)) {
				key = key.replaceAll(" ", "+");
				String[] keys = SecretUtil.decrypt(key, secretPwd).split(SPLIT);
				long time = Long.parseLong(keys[1]);
				if (System.currentTimeMillis() - time <= 3600000) {// 1小时以内
					String uid = keys[0];
					userService.resetPwd2(uid, pwd);
					info = "密码重置成功！";
				}
			}
		} catch (Exception err) {
			log.error(err.getMessage(), err);
			info = "密码重置失败！";
		}
		getRequest().setAttribute("info", info);
		return "showInfo";
	}

	/**
	 * 直接获取资源
	 * 
	 * @return
	 */
	public String getPic() {
		try {
			HttpServletRequest req = getRequest();
			String name = ServletRequestUtils.getStringParameter(req, "name");
			if (null != name && !"".equals(name)) {
				byte[] b = FileOP.readFile(CodeUtil.picPath + name);
				OutUtil.outFile(b, name, getResponse());
			}
		} catch (Exception err) {
			log.error(err.getMessage(), err);
		}
		return null;
	}

	/**
	 * 进入宝宝资料界面
	 * 
	 * @return
	 */
	public String viewBabyInfo() {
		return "viewBabyInfo";
	}

	/**
	 * 提供栏位登录信息
	 * 
	 * @return
	 */
	public String getCurrentUser() {
		Map<String, Object> map = CodeUtil.getJsonMap();
		map.put("code", CodeUtil.SUCCESS);
		map.put("info", session.get(CodeUtil.SessionKey));
		OutUtil.outJson(map, getResponse());
		return null;
	}

	/**
	 * 填写宝宝资料
	 * 
	 * @return
	 */
	public String updateBabyInfo() {
		Map<String, Object> map = CodeUtil.getJsonMap();
		try {
			HttpServletRequest req = getRequest();
			String babySex = ServletRequestUtils.getStringParameter(req, "babySex");
			String babyBirthday = ServletRequestUtils.getStringParameter(req, "babyBirthday");
			String babyName = ServletRequestUtils.getStringParameter(req, "babyName");
			String babyHeight = ServletRequestUtils.getStringParameter(req, "babyHeight", "");
			String babyWeight = ServletRequestUtils.getStringParameter(req, "babyWeight", "");
			UserVO vo = (UserVO) session.get(CodeUtil.SessionKey);
			frontSysService.updateBabyInfo(vo.getUserId(), picFileName, pic, babySex, babyBirthday, babyName, babyHeight, babyWeight);

			session.put(CodeUtil.SessionKey, userService.getUser(vo.getUserId()));
			map.put("code", CodeUtil.SUCCESS);
		} catch (Exception err) {
			log.error(err.getMessage(), err);
			map.put("code", CodeUtil.UNKOWN_ERR);
		}
		OutUtil.outJson(map, getResponse());
		return null;
	}

	/**
	 * 进入投诉建议页面
	 * 
	 * @return
	 */
	public String viewSuggest() {
		// 分类树
		getRequest().setAttribute("treeMap", classifyService.getFrontClass());
		return "viewSuggest";
	}

	/**
	 * 新增投诉建议
	 * 
	 * @return
	 */
	public String addSuggest() {
		Map<String, Object> map = CodeUtil.getJsonMap();
		try {
			HttpServletRequest req = getRequest();
			String title = ServletRequestUtils.getStringParameter(req, "title");
			String phone = ServletRequestUtils.getStringParameter(req, "phone");
			String content = ServletRequestUtils.getStringParameter(req, "content");

			UserVO userVO = (UserVO) session.get(CodeUtil.SessionKey);
			suggestService.add(title, phone, content, picFileName, pic, userVO.getAccount(), req.getRemoteAddr());
			map.put("code", CodeUtil.SUCCESS);
		} catch (Exception err) {
			log.error(err.getMessage(), err);
			map.put("code", CodeUtil.UNKOWN_ERR);
		}
		OutUtil.outJson(map, getResponse());
		return null;
	}

	/**
	 * 百度第三方回调接口
	 * 
	 * @return
	 */
	public String baiduLoginCallBack() {
		Map<String, Object> map = CodeUtil.getJsonMap();
		try {
			HttpServletRequest req = getRequest();
			HttpServletResponse res = getResponse();
			String access_token = ServletRequestUtils.getStringParameter(req, "access_token");
			if (null != access_token) {
				UserVO vo = frontSysService.baiduLoginCallBack(access_token);
				res.addCookie(toCookie(vo.getAccount(), vo.getPwd()));
				session.put(CodeUtil.SessionKey, vo);
			}
			map.put("code", CodeUtil.SUCCESS);
		} catch (Exception err) {
			log.error(err.getMessage(), err);
			map.put("code", CodeUtil.UNKOWN_ERR);
		}
		OutUtil.outJson(map, getResponse());
		return null;
	}

	/**
	 * QQ第三方回调接口
	 * 
	 * @return
	 */
	public String qqLoginCallBack() {
		try {
			HttpServletRequest req = getRequest();
			HttpServletResponse res = getResponse();
			String access_token = ServletRequestUtils.getStringParameter(req, "access_token");
			if (null != access_token) {
				UserVO vo = frontSysService.qqLoginCallBack(access_token);
				res.addCookie(toCookie(vo.getAccount(), vo.getPwd()));
				session.put(CodeUtil.SessionKey, vo);
				OutUtil.outString("<script type=\"text/javascript\">window.opener.checkToken();window.close();</script>", res);
			} else {
				OutUtil.outString("<script type=\"text/javascript\">var p=location.hash;location.href=\"" + CodeUtil.webNetName + "/frontSys!qqLoginCallBack.action?\"+p.substr(1);</script>", res);
			}
		} catch (Exception err) {
			log.error(err.getMessage(), err);
		}
		return null;
	}

	private Cookie toCookie(String account, String pwd) throws Exception {
		String s = SecretUtil.encrypt(account + SPLIT + pwd, secretPwd);
		String v = URLEncoder.encode(s, "UTF-8");
		Cookie cookie = new Cookie(CodeUtil.CookieKey, v);
		cookie.setMaxAge(2592000);
		return cookie;
	}

	// 上传文件域对象
	private File pic;
	// 上传文件名
	private String picFileName;

	public void setPic(File pic) {
		this.pic = pic;
	}

	public void setPicFileName(String picFileName) {
		this.picFileName = picFileName;
	}
}
